public class 合并K个升序链表 {

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeKLists(ListNode[] lists) {
        return dfs(lists,0,lists.length - 1);
    }

    public ListNode dfs (ListNode[] lists,int left, int right) {
        if (left > right) {
            return null;
        }
        if (left == right) {
            return lists[left];
        }
        int mid = (left + right) / 2;
        ListNode l = dfs(lists,left,mid);
        ListNode r = dfs(lists,mid + 1,right);
        return mergeLinkedList(l,r);
    }

    public ListNode mergeLinkedList (ListNode head1,ListNode head2) {
        ListNode ans = new ListNode();
        ListNode cur = ans;
        while (head1 != null && head2 != null){
            if (head1.val < head2.val) {
                cur.next = head1;
                head1 = head1.next;
                cur = cur.next;
            } else {
                cur.next = head2;
                head2 = head2.next;
                cur = cur.next;
            }
        }
        if (head1 == null) cur.next = head2;
        if (head2 == null) cur.next = head1;
        return ans.next;
    }
}
